<template>
    <div class="admin-login-page">
      <!-- 动态背景 -->
      <div class="background">
        <canvas class="particle-canvas"></canvas>
        <div class="floating-shapes">
          <div style="width: 150px; height: 150px; top: 10%; left: 5%"></div>
          <div style="width: 100px; height: 100px; top: 60%; left: 80%"></div>
          <div style="width: 120px; height: 120px; top: 30%; left: 70%"></div>
        </div>
      </div>
  
      <div class="container">
        <div class="admin-login-card">
          <div class="admin-icon">
            <div class="icon-circle">
              <span class="icon-text">⚙️</span>
            </div>
          </div>
          <h2 class="title">管理员登录</h2>
          <div v-if="errorMessage" class="error-message">{{ errorMessage }}</div>
          <div v-if="successMessage" class="success-message">{{ successMessage }}</div>
  
          <div class="form-container">
            <div class="form-group">
              <label for="username">管理员账户</label>
              <input 
                id="username" 
                v-model="username" 
                type="text" 
                placeholder="请输入管理员账户" 
                required 
              />
            </div>
  
            <div class="form-group">
              <label for="password">管理员密码</label>
              <input 
                id="password" 
                v-model="password" 
                type="password" 
                placeholder="请输入管理员密码" 
                required 
              />
            </div>
  
            <div class="form-group">
              <label>人脸验证</label>
              <div class="face-recognition">
                <!-- #ifdef H5 -->
                <div id="video-container" class="video-container"></div>
                <div class="face-buttons">
                  <button type="button" @click="startCamera" :disabled="isCameraActive">开启摄像头</button>
                  <button type="button" @click="captureFace" :disabled="!isCameraActive">拍照</button>
                </div>
                <!-- #endif -->
  
                <!-- #ifdef APP-PLUS || MP-WEIXIN -->
                <camera
                  v-if="isCameraActive"
                  device-position="front"
                  flash="off"
                  @error="uni.showToast({ title: '摄像头错误', icon: 'none' })"
                  style="width: 100%; height: 300px;"
                ></camera>
                <!-- #endif -->
  
                <div v-if="faceImage" class="face-preview">
                  <image :src="faceImage" mode="aspectFit" style="width: 200px; height: 200px;" />
                </div>
              </div>
            </div>
  
            <button class="login-btn" type="button" @click="adminLogin" :disabled="loggingIn">
              {{ loggingIn ? '登录中...' : '管理员登录' }}
            </button>
          </div>
  
          <div class="links">
            <text @click="goToUserLogin">普通用户登录</text>
          </div>
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted, onUnmounted } from 'vue';
  
  // 表单数据
  const username = ref('');
  const password = ref('');
  
  // 状态控制
  const errorMessage = ref('');
  const successMessage = ref('');
  const loggingIn = ref(false);
  
  // 摄像头相关
  const videoElement = ref(null);
  const isCameraActive = ref(false);
  const faceImage = ref('');
  const stream = ref(null);
  
  const startCamera = async () => {
    try {
      // #ifdef H5
      const stream = await navigator.mediaDevices.getUserMedia({
        video: { facingMode: 'user' },
        audio: false
      });
      stream.value = stream;
  
      const container = document.getElementById('video-container');
      if (videoElement.value) {
        container.removeChild(videoElement.value);
      }
  
      const video = document.createElement('video');
      video.autoplay = true;
      video.muted = true;
      video.playsInline = true;
      video.style.width = '100%';
      video.style.maxWidth = '100%';
      video.style.height = '250px';
      video.style.background = 'black';
      video.style.objectFit = 'cover';
      video.style.borderRadius = '16px';
      video.style.marginBottom = '16px';
      video.style.boxShadow = '0 4px 20px rgba(0,0,0,0.15)';
  
      video.srcObject = stream;
      container.appendChild(video);
      videoElement.value = video;
      isCameraActive.value = true;
      // #endif
  
      // #ifdef APP-PLUS || MP-WEIXIN
      const context = uni.createCameraContext();
      if (context) {
        isCameraActive.value = true;
      }
      // #endif
    } catch (error) {
      console.error('摄像头访问失败:', error);
      uni.showToast({
        title: '摄像头权限被拒绝或设备不支持',
        icon: 'none'
      });
      isCameraActive.value = false;
    }
  };
  
  const captureFace = () => {
    // #ifdef H5
    if (!videoElement.value) return;
    
    const video = videoElement.value;
    if (!video.videoWidth || !video.videoHeight) {
      uni.showToast({
        title: '视频未就绪，请稍候',
        icon: 'none'
      });
      return;
    }
    
    const canvas = document.createElement('canvas');
    const context = canvas.getContext('2d');
    if (!context) {
      uni.showToast({
        title: '无法创建画布上下文',
        icon: 'none'
      });
      return;
    }
    
    canvas.width = video.videoWidth;
    canvas.height = video.videoHeight;
    
    try {
      context.drawImage(video, 0, 0, canvas.width, canvas.height);
      faceImage.value = canvas.toDataURL('image/jpeg');
      stopCamera();
      
      uni.showToast({
        title: '人脸照片已采集',
        icon: 'success'
      });
    } catch (error) {
      console.error('截图失败:', error);
      uni.showToast({
        title: '截图失败，请重试',
        icon: 'none'
      });
    }
    // #endif
  
    // #ifdef APP-PLUS || MP-WEIXIN
    if (!isCameraActive.value) return;
    
    const cameraContext = uni.createCameraContext();
    if (cameraContext) {
      cameraContext.takePhoto({
        quality: 'high',
        success: (res) => {
          faceImage.value = res.tempImagePath;
          stopCamera();
          uni.showToast({
            title: '人脸照片已采集',
            icon: 'success'
          });
        },
        fail: (err) => {
          console.error('拍照失败:', err);
          uni.showToast({
            title: '拍照失败',
            icon: 'none'
          });
        }
      });
    }
    // #endif
  };
  
  const stopCamera = () => {
    // #ifdef H5
    if (stream.value) {
      stream.value.getTracks().forEach(track => track.stop());
      stream.value = null;
    }
    // #endif
    isCameraActive.value = false;
  };
  
  const adminLogin = async () => {
    if (!username.value || !password.value) {
      uni.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }
  
    loggingIn.value = true;
    errorMessage.value = '';
    successMessage.value = '';
  
    try {
      // TODO: 这里需要实现后端接口
      // const response = await fetch("${NETWORK_CONFIG.API_BASE_URL}/admin/login", {
      //   method: "POST",
      //   headers: { "Content-Type": "application/json" },
      //   body: JSON.stringify({
      //     username: username.value,
      //     password: password.value,
      //     faceImage: faceImage.value
      //   }),
      // });
  
      // 模拟登录成功
      await new Promise(resolve => setTimeout(resolve, 1500));
      
      successMessage.value = '管理员登录成功！';
      
      uni.showToast({
        title: '管理员登录成功',
        icon: 'success'
      });
      
      // 登录成功后跳转到管理员后台
      setTimeout(() => {
        // TODO: 跳转到管理员后台页面
        // uni.navigateTo({
        //   url: '/pages/admin/dashboard'
        // });
        console.log('跳转到管理员后台');
      }, 2000);
      
    } catch (error) {
      errorMessage.value = '登录失败: ' + error.message;
      
      uni.showToast({
        title: '登录失败',
        icon: 'none'
      });
    } finally {
      loggingIn.value = false;
    }
  };
  
  const goToUserLogin = () => {
    uni.navigateTo({
      url: '/pages/auth/login/index'
    });
  };
  
  onUnmounted(() => {
    stopCamera();
  });
  
  onMounted(() => {
    // #ifdef H5
    // 移动端键盘弹出处理
    const handleResize = () => {
      const vh = window.innerHeight * 0.01;
      document.documentElement.style.setProperty('--vh', `${vh}px`);
    };
    
    window.addEventListener('resize', handleResize);
    handleResize();
    
    // 防止iOS Safari中的橡皮筋效果
    document.body.addEventListener('touchmove', (e) => {
      if (e.target.closest('.admin-login-card')) {
        e.preventDefault();
      }
    }, { passive: false });
    // #endif
  });
  </script>
  
  <style scoped>
  body, html {
    margin: 0;
    padding: 0;
    width: 100vw;
    overflow-x: hidden;
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', 'Helvetica Neue', Helvetica, Arial, sans-serif;
    background: #f6f8fa;
  }
  
  .admin-login-page {
    min-height: 100vh;
    width: 100vw;
    display: flex;
    align-items: center;
    justify-content: center;
    background: #667eea;
    padding: 0;
    box-sizing: border-box;
    overflow-x: hidden;
    position: relative;
    z-index: 2;
  }
  
  .container {
    width: 100vw;
    min-height: 100vh;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0;
    box-sizing: border-box;
  }
  
  .admin-login-card {
    width: 100%;
    max-width: 450px;
    margin: 0 auto;
    background: #fff;
    border-radius: 20px;
    /* box-shadow: 0 8px 32px rgba(0,0,0,0.1);  // WXSS不支持 */
    padding: 30px 24px;
    display: flex;
    flex-direction: column;
    gap: 20px;
    /* backdrop-filter: blur(10px); // WXSS不支持 */
    border: 1px solid #eee;
  }
  
  .admin-icon {
    display: flex;
    justify-content: center;
    margin-bottom: 10px;
  }
  
  .icon-circle {
    width: 80px;
    height: 80px;
    border-radius: 50%;
    background: #4f8cff;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  
  .icon-text {
    font-size: 2rem;
    color: white;
  }
  
  .title {
    font-size: 1.8rem;
    font-weight: 700;
    color: #1a1a1a;
    margin-bottom: 5px;
    text-align: center;
    letter-spacing: -0.5px;
  }
  
  .form-container {
    display: flex;
    flex-direction: column;
    gap: 16px;
  }
  
  .form-group {
    display: flex;
    flex-direction: column;
    gap: 8px;
  }
  
  .form-group label {
    font-size: 0.95rem;
    color: #4a5568;
    font-weight: 500;
    margin-bottom: 2px;
  }
  
  input, select {
    padding: 16px 14px;
    border: 2px solid #e2e8f0;
    border-radius: 12px;
    font-size: 1rem;
    outline: none;
    background: #f8fafc;
    font-family: inherit;
  }
  
  input:focus, select:focus {
    border: 2px solid #4f8cff;
    background: #fff;
  }
  
  .login-btn {
    width: 100%;
    padding: 18px 0;
    background: #4f8cff;
    color: #fff;
    border: none;
    border-radius: 12px;
    font-size: 1.1rem;
    font-weight: 700;
    cursor: pointer;
    margin-top: 10px;
  }
  
  .login-btn:disabled {
    background: #cbd5e1;
    cursor: not-allowed;
  }
  
  .links {
    text-align: center;
    margin-top: 15px;
    font-size: 0.9rem;
    line-height: 1.5;
  }
  
  .links text {
    color: #4f8cff;
    text-decoration: none;
    margin: 0 8px;
    cursor: pointer;
    font-weight: 500;
    padding: 4px 8px;
    border-radius: 6px;
  }
  
  .error-message {
    background: #fef2f2;
    color: #dc2626;
    border-radius: 12px;
    padding: 14px 16px;
    font-size: 0.9rem;
    text-align: center;
    border: 1px solid #fecaca;
    font-weight: 500;
  }
  
  .success-message {
    background: #f0fdf4;
    color: #16a34a;
    border-radius: 12px;
    padding: 14px 16px;
    font-size: 0.9rem;
    text-align: center;
    border: 1px solid #bbf7d0;
    font-weight: 500;
  }
  
  .face-recognition {
    display: flex;
    flex-direction: column;
    gap: 12px;
    align-items: center;
  }
  
  .face-buttons {
    display: flex;
    gap: 8px;
    justify-content: center;
    margin-top: 12px;
    flex-wrap: wrap;
  }
  
  .face-buttons button {
    padding: 12px 16px;
    background: #4f8cff;
    color: #fff;
    border: none;
    border-radius: 10px;
    font-size: 0.9rem;
    font-weight: 600;
    cursor: pointer;
    min-width: 80px;
  }
  
  .face-buttons button:disabled {
    background: #cbd5e1;
    cursor: not-allowed;
  }
  
  .video-container {
    width: 100%;
    max-width: 100%;
    height: 250px;
    background: #000;
    border-radius: 16px;
    overflow: hidden;
    margin-bottom: 16px;
  }
  
  .face-preview {
    margin-top: 12px;
  }
  
  .background {
    position: absolute;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    z-index: 0;
    pointer-events: none;
  }
  .floating-shapes {
    position: absolute;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    pointer-events: none;
    z-index: 1;
  }
  .floating-shapes > div {
    position: absolute;
    border-radius: 50%;
    background: rgba(255,255,255,0.08);
  }
  .particle-canvas {
    position: absolute;
    top: 0;
    left: 0;
    width: 100vw;
    height: 100vh;
    z-index: 0;
    pointer-events: none;
  }
  </style> 